var scripts = [null, '../assets/js/bootstrap-multiselect.js', "../assets/js/fuelux/fuelux.wizard.js", '../assets/js/bootstrap-tagsinput.js',
  "../assets/js/jquery.validate.js",
  '../assets/ueditor/ueditor.config.js',
  '../assets/ueditor/ueditor.all.min.js',
  null
]


$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  const hasValue = (val) => !!val
  const doAlert = (val, cb) => bootbox.alert(val, cb)
  jQuery(function ($) {
    function getString (val) {
      return '' + val
    }
    /**
     * focusIDs 攻略焦点图
     * */
    var focusIDs = [];
    var strategyId = $utils.string.getQueryParam("id");
    let alreadySelectedResources = [];
    var $destinationId = $("#destinationId");
    const $btnSave = $('#btnSave')
    const $steps = $('.steps > li')

    // 实例化编辑器
    const ue = window.UE.getEditor('editorContainer')

    $destinationId.multiselect({
      enableFiltering: true,
      buttonClass: 'btn btn-white btn-primary',
      maxHeight: 200,
      numberDisplayed: 1,
      templates: {
        button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
        ul: '<ul class="multiselect-container dropdown-menu"></ul>',
        filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
        filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
        li: '<li><a href="javascript:void(0);"><label></label></a></li>',
        divider: '<li class="multiselect-item divider"></li>',
        liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
      }
    });

    renderDestination("destinationId");
    $destinationId.multiselect('rebuild');
    getStrategyInfo();

    $('#fuelux-wizard-container')
      .ace_wizard({
        step: 1,//optional argument. wizard will jump to step "2" at first
      })
      .on('actionclicked.fu.wizard', function (e, info) {
        if (info.step == 1 && info.direction == 'next') {}
        if (info.step == 2 && info.direction == 'next') {}
      })
      .on('finished.fu.wizard', function (e) {});

    $btnSave.click(function (e) {
      // 判断当前是第几步
      const step = parseInt($steps.filter('.active').data('step'), 10)
      if (step === 1) {
        if ($(".mainImg").attr("data-id") == "") {
          alert("请添加主图")
          return false
        }
        if ($(".focusedImg").attr("data-id") == "") {
          alert("请添加焦点图")
          return false
        }
        if($(".hotImg").attr("data-id") == "" && $("#hotCheckBox").is(':checked') ){
          alert("请添加热门图")
          return false
        }
        if($(".recommendImg").attr("data-id") == "" && $("#recommendCheckBox").is(':checked') ){
          alert("请添加推荐图")
          return false
        }
        updateStrategyBaseInfo()
      } else if (step === 2) {
        updateStrategyTrafficInfo();
      } else if (step === 3) {
        updateStrategyRefInfo()
      }
    });

    $('.btn-next').click(function (e) {
      const step = parseInt($steps.filter('.active').data('step'), 10);
      if (step === 3) {
        queryRefList('1')
        queryRefList('2')
        queryRefList('3')
      }
    });

    $("#webuploader-pick-main").click(function () {
      resourceModel(1, 10, 10, function (data) {//
        $(".mainImg").attr("src", data[0].src);
        $(".mainImg").attr("data-id", data[0].id);
      })
    })

    $("#webuploader-pick-focused").click(function () {
      resourceModel(1, 10, 10, function (data) {//
        $(".focusedImg").attr("src", data[0].src);
        $(".focusedImg").attr("data-id", data[0].id);
      })
    })
    $("#webuploader-pick-hot").click(function () {
      resourceModel(1, 10, 10, function (data) {//
        $(".hotImg").attr("src", data[0].src);
        $(".hotImg").attr("data-id", data[0].id);
      })
    })
    $("#webuploader-pick-recommend").click(function () {
      resourceModel(1, 10, 10, function (data) {//
        $(".recommendImg").attr("src", data[0].src);
        $(".recommendImg").attr("data-id", data[0].id);
      })
    })

    function getStrategyInfo() {
      var url = $utils.ajax.setUrl("sysStrategy/getStrategyById");
      var params = {}
      params.strategyId = strategyId//攻略Id
      axios.post(url, params).then(function (response) {
        if (response.code === "10000") {
          const body = response.body || {}
          const baseInfo = body.baseInfo || {}
          const refItem = body.refItem || []
          const resource = body.resource || []
          const typeId = body.typeId || []

          // 显示攻略基本信息
          $('#strategyName').val(baseInfo.strategyName || '');
          ue.ready(() => {
            ue.setContent(baseInfo.strategyDetail || '');
          })
          $destinationId.multiselect('select', getString(baseInfo.destinationId) || '');
          $destinationId.multiselect('rebuild');
          $("#strategyTitle").val(baseInfo.strategyTitle)//攻略主题
          $("#strategySubTitle").val(baseInfo.strategySubTitle)//攻略副主题
          $('#destinationDetail').val(baseInfo.destinationDetail || '');
          $("#numCollect").val(baseInfo.numCollect || 0);
          $("#numComment").val(baseInfo.numComment || 0);
          $("#numShare").val(baseInfo.numShare || 0);
          typeId.forEach((item, idx) => {
            const tempTypeId = item.TYPE_ID || ''
            const $elem = $(`#strategyType input[value="${tempTypeId}"]`)
            if ($elem.length === 1) {
              $elem.prop('checked', true)
              // $('#productTypeRef input[value=' + val + ']').prop('checked', true)
            }
          })
          // 主图
          const mainImg = resource.filter(item => getString(item.FIRST_FLAG) === '1')
          console.info("mainImg="+mainImg)
          if (mainImg.length === 1) {
            const $mainImg = $('#mainImg')
            $mainImg.prop('src', mainImg[0].IMAGE_URL)
            $mainImg.attr('data-id', mainImg[0].RESOURCE_ID)
          }
          // 焦点图
          const focusedImg = resource.filter(item => getString(item.FIRST_FLAG) === '2')
          if (focusedImg.length === 1) {
            const $focusedImg = $('#focusedImg')
            $focusedImg.prop('src', focusedImg[0].IMAGE_URL)
            $focusedImg.attr('data-id', focusedImg[0].RESOURCE_ID)
          }
          //热门图
          const hotImg = resource.filter(item => getString(item.FIRST_FLAG) === '3')
          if (hotImg.length === 1) {
            const $hotImg = $('#hotImg')
            $hotImg.prop('src', hotImg[0].IMAGE_URL)
            $hotImg.attr('data-id', hotImg[0].RESOURCE_ID)
          }
          //推荐图
          const recommendImg = resource.filter(item => getString(item.FIRST_FLAG) === '4')
          if (recommendImg.length === 1) {
            const $recommendImg = $('#recommendImg')
            $recommendImg.prop('src', recommendImg[0].IMAGE_URL)
            $recommendImg.attr('data-id', recommendImg[0].RESOURCE_ID)
          }
         /* const imgslistFocus = resource.filter(item => getString(item.FIRST_FLAG) === '0')
          if (imgslistFocus.length > 0) {
            let html = ''
            const itemHtml = `
              <li class="item">
                <div class="thumb">
                  <img data-id="{{imgId}}" src="{{imgUrl}}">
                  <span onclick="delStrategyImg(this)" class="btn btn-sm btn-white">
                    <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除
                  </span>
                </div>
              </li>
            `
            imgslistFocus.forEach(item => {
              focusIDs.push(item.RESOURCE_ID || '')
              html += itemHtml
                .replace('{{imgId}}', item.RESOURCE_ID || '')
                .replace('{{imgUrl}}', item.IMAGE_URL || '')
            })
            $('#imgslistFocus').append(html)
          }*/

          // 交通、签证信息
          $('#strategyTraffic').val(baseInfo.strategyTraffic || '')
          $('#strategyVisa').val(baseInfo.strategyVisa || '')

          // 保存之前已经选择了的资源数据（第三步用）
          alreadySelectedResources = refItem
        } else {
          bootbox.alert('查询攻略信息失败！')
        }
      })
    }

    function updateStrategyRefInfo() {
      const getIds = (wrapperSelector) => {
        const $wrapper = $(wrapperSelector)
        const arr = []
        $wrapper.find('.card.active').each(function (idx, elem) {
          arr.push($(elem).data('id') || '')
        })
        return arr.join(',')
      }
      var url = $utils.ajax.setUrl("sysStrategy/insertOrUpdateStrategyRefInfo");
      var params = {}
      params.strategyId = strategyId//攻略Id
      params.foodsIds = getIds('#cardsFood')
      params.scenicIds = getIds('#cardsScene')
      params.shoppingIds = getIds('#cardsPurchase')
      axios.post(url, params).then(function (response) {
        if (response.code == "10000") {
          bootbox.alert("修改攻略关联细项成功", () => {
            // 添加成功后返回列表页
            window.location.href = '/views/index.html#page/strategy/strategy/list'
          })
        } else {
          bootbox.alert("修改攻略关联细项失败")
        }
      })
    }

    function updateStrategyTrafficInfo() {
      var url = $utils.ajax.setUrl("sysStrategy/insertOrUpdateStrategyTrafficInfo");
      var params = {}
      params.strategyId = strategyId//攻略Id
      params.strategyTraffic = $("#strategyTraffic").val()//交通
      params.strategyVisa = $("#strategyVisa").val()//签证
      axios.post(url, params).then(function (response) {
        if (response.code == "10000") {
          bootbox.alert("修改交通/签证成功")
        } else {
          bootbox.alert("修改交通/签证失败")
        }
      })
    }

    /**修改攻略基本信息*/
    function updateStrategyBaseInfo() {
      var url = $utils.ajax.setUrl("sysStrategy/insertOrUpdateStrategyBaseInfo");

      const strategyName = $("#strategyName").val()
      const strategyTitle = $("#strategyTitle").val()
      const strategySubTitle = $("#strategySubTitle").val()
      const strategyDetail = ue.getContent()
      const destinationDetail = $('#destinationDetail').val()
      const resourceId = $(".mainImg").attr("data-id");
      const focusedId =  $(".focusedImg").attr("data-id");
      const hotResourcesId = $(".hotImg").attr("data-id");
      const recommendResourcesId = $(".recommendImg").attr("data-id");
      if (!hasValue(strategyName)) {
        doAlert('请输入攻略名称！')
        return false
      }
      if(!hasValue(strategyTitle)){
        doAlert('请输入攻略标题！')
        return false
      }
      if(!hasValue(strategySubTitle)){
        doAlert('请输入攻略副标题！')
        return false
      }
      if(!hasValue(strategyDetail)){
        doAlert('请输入攻略描述！')
        return false
      }
      if(!hasValue(destinationDetail)){
        doAlert('请输入目的地描述！')
        return false
      }


      var params = {}
      params.strategyId = strategyId//攻略Id
      params.strategyName = strategyName //攻略名称
      params.strategyTitle = strategyTitle //攻略主题
      params.strategySubTitle = strategySubTitle //攻略副主题
      params.strategyDetail = strategyDetail //攻略描述
      params.destinationId = $("#destinationId").val()//目的地
      params.destinationDetail = destinationDetail //目的地描述
      params.resourceId = resourceId;
      params.focusedId = focusedId;
      params.hotResourcesId = hotResourcesId;
      params.recommendResourcesId = recommendResourcesId;
      params.numCollect = $("#numCollect").val()
      params.numComment = $("#numComment").val()
      params.numShare = $("#numShare").val()
      var strategyTypeArr = []
      $("#strategyType input:checked").each(function (index, ele) {
        strategyTypeArr.push($(this).val())
      })
      if (strategyTypeArr.length > 0) {
        params.strategyTypes = strategyTypeArr.join(',')
      }
      axios.post(url, params).then(function (response) {
        if (response.code == "10000") {
          bootbox.alert("修改攻略成功")
        } else {
          bootbox.alert("修改攻略失败")
        }
      })
    }

    /**攻略图片*/
    $("#webuploader-pick-focus").click(function () {
      resourceModel(2, 10, 10, function (data) {
        $.each(data, function (key, val) {
          if ($.inArray(val.id, focusIDs) == -1) {
            focusIDs.push(val.id);
            var html = '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
              '<span onclick="delStrategyImg(this,1)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
            $(".imgslist-focus").append(html)
          }
        })
      })
    })

    function delStrategyImg(obj) {
      $(obj).parents(".item").remove()
      removeArrItem(focusIDs, $(obj).prev("img").attr("data-id"))
    }

    window.delStrategyImg = delStrategyImg;

    function removeItem(obj) {
      $(obj).parents(".form-group").remove()
    }

    window.removeItem = removeItem;

    /**
     * 查询美食、景点、购物信息
     * @param itemType {string} 1=美食 2=景点 3=购物
     */
    function queryRefList (itemType) {
      itemType = '' + itemType
      const url = $utils.ajax.setUrl("sysStrategy/queryRefList")
      const requestData = {
        destinationId: $('#destinationId').val(),
        itemType
      }
      axios.post(url, requestData).then(res => {
        if (res.code === '10000') {
          const prefix = (() => {
            switch (itemType) {
              case '1': return 'FOOD'
              case '2': return 'SCENIC'
              case '3': return 'SHOPPING'
              default: return ''
            }
          })()
          const list = (res.body || []).map(item => {
            return {
              id: item[prefix + '_ID'],
              imgUrl: item.IMAGE_URL,
              name: item[prefix + '_NAME']
            }
          })
          renderRefList(itemType, list)
        } else {
          const itemTypeText = (() => {
            switch (itemType) {
              case '1': return '美食'
              case '2': return '景点'
              case '3': return '购物'
              default: return ''
            }
          })()
          bootbox.alert(`查询${itemTypeText}信息失败`)
        }
      })
    }

    /**
     * 渲染美食、景点、购物信息到页面上
     * @param itemType {string} 1=美食 2=景点 3=购物
     * @param data
     */
    function renderRefList (itemType, data) {
      itemType = '' + itemType
      const targetId = (() => {
        switch (itemType) {
          case '1': return 'cardsFood'
          case '2': return 'cardsScene'
          case '3': return 'cardsPurchase'
          default: return ''
        }
      })()
      const $wrapper = $('#' + targetId)
      const itemHtml = `
        <li class="card {{activeClass}}" data-id="{{id}}">
          <div class="card-img" style="background-image: url('{{imgUrl}}');"></div>
          <div class="card-name">{{name}}</div>
        </li>
      `
      let html = ''
      data.forEach(item => {
        const isActive = alreadySelectedResources.filter(d => {
          return getString(d.ITMES_TYPE) === itemType && getString(d.ITEMS_ID) === getString(item.id)
        }).length > 0
        html += itemHtml
          .replace('{{activeClass}}', isActive ? 'active' : '')
          .replace('{{id}}', item.id)
          .replace('{{imgUrl}}', item.imgUrl)
          .replace('{{name}}', `${item.name}`)
      })
      $wrapper.html(html)
    }

    /**
     * 点击美食、景点、购物卡片，切换勾选状态
     */
    $('.cards').on('click', '.card', function (e) {
      const $this = $(this)
      $this.toggleClass('active');
    })
  })
});
